package pjkanri.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import pjkanri.entity.Issure;

public class IssureDAO {

	/**
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Issure> findAll() throws DAOException {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		Criteria criteria = session.createCriteria(Issure.class);
		List<Issure> issuelist = criteria.list();

		return issuelist;
	}

	/**
	 * @param projectId
	 * @return
	 */
	public List<Issure> findIssureByProjectID(Integer projectId)
			throws DAOException {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		Criteria criteria = session.createCriteria(Issure.class);
		criteria.add(Restrictions.eq("project_id", projectId));

		@SuppressWarnings("unchecked")
		List<Issure> issuelist = criteria.list();

		return issuelist;
	}

	/**
	 * @param issue
	 * @return
	 * @throws DAOException
	 */
	public void insert(Issure issue) throws DAOException {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		issue.setIssure_id(getMaxId() + 1);
		session.save(issue);
	}

	/**
	 * @return
	 * @throws DAOException
	 */
	private Integer getMaxId() throws DAOException {

		Integer maxId = 0;
		String sql = "SELECT Max(issure_id) as max FROM issure ";

		DataSource ds = DataSourceFactory.getDataSource();

		try (Connection conn = ds.getConnection();
				Statement pstmt = conn.createStatement()) {

			try (ResultSet rs = pstmt.executeQuery(sql)) {

				if (rs.next()) {
					if (rs.getString("max") == null)
						return 0;
					maxId = Integer.parseInt(rs.getString("max"));
				}
			}

		} catch (SQLException e) {
			throw new DAOException(e);
		}
		return maxId;
	}
}
